package com.itheima.bakery.demos.web.service;

import com.itheima.bakery.demos.web.model.ShippingAddress;
import com.itheima.bakery.demos.web.Repositories.ShippingAddressRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ShippingAddressService {

    @Autowired
    private ShippingAddressRepository shippingAddressRepository;

    // 获取所有收货地址
    public List<ShippingAddress> getAllShippingAddresses() {
        return shippingAddressRepository.findAll();
    }

    // 根据ID获取收货地址
    public ShippingAddress getShippingAddressById(Integer id) {
        return shippingAddressRepository.findById(id).orElse(null);
    }

    // 根据用户ID获取收货地址
    public List<ShippingAddress> getShippingAddressesByUserId(Integer userId) {
        return shippingAddressRepository.findByUserId(userId);
    }

    // 创建收货地址
    public ShippingAddress createShippingAddress(ShippingAddress shippingAddress) {
        return shippingAddressRepository.save(shippingAddress);
    }

    // 更新收货地址
    public ShippingAddress updateShippingAddress( Integer addressId, ShippingAddress newAddressInfo) {
        // 根据ID查找要更新的收货地址
        ShippingAddress address = shippingAddressRepository.findById(addressId).orElse(null);
        if (address == null) {
            throw new RuntimeException("Address not found");
        }
        

        // 更新收货地址信息
        address.setRecipientName(newAddressInfo.getRecipientName());
        address.setPhone(newAddressInfo.getPhone());
        address.setAddress(newAddressInfo.getAddress());

        // 保存更新后的收货地址
        return shippingAddressRepository.save(address);
    }

    // 删除收货地址
    public void deleteShippingAddress(Integer id) {
        shippingAddressRepository.deleteById(id);
    }
}